package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @CacheEvict(value = "dish",allEntries = true)
    @PostMapping
    public R addDish(@RequestBody DishDto dishDto) {

        dishService.saveWithDishFlavor(dishDto);

        //添加成功后清空缓存数据
        /*String key = "dish_" + dishDto.getCategoryId() +"_1";
        redisTemplate.delete(key);*/

        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R getDishByPage(Integer page, Integer pageSize, String name) {
        Map<Object, Object> data = null;

        IPage<Dish> pageinfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        dishService.page(pageinfo, lqw);

        List<Dish> dishes = pageinfo.getRecords();
        List<DishDto> records = new ArrayList<>();
        for (Dish dish : dishes) {
            //根据categoryId获取category对象,进而获取name
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            //将dish中的数据和categoryName封装到dishdto对象中
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            dishDto.setCategoryName(categoryName);
            //将dishDto对象添加到records集合中
            records.add(dishDto);
        }

        long total = pageinfo.getTotal();
        data = new HashMap<>();
        data.put("records", records);
        data.put("total", total);

        return R.success(data);
    }

    //回显数据
    @GetMapping("/{id}")
    public R getDishById(@PathVariable Long id) {

        Dish dish = dishService.getById(id);
        //根据categoryId获取category对象,进而获取name
        Category category = categoryService.getById(dish.getCategoryId());
        String categoryName = category.getName();

        //将dish中的数据和categoryName封装到dishdto对象中
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setCategoryName(categoryName);

        //根据dish_id查询dishFlavor表,封装到dishdto对象中
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, id);
        List<DishFlavor> flavors = dishFlavorService.list(lqw);
        dishDto.setFlavors(flavors);

        return R.success(dishDto);
    }

    @PutMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R updateDish(@RequestBody DishDto dishDto) {

        //修改dish表中的基本数据
        dishService.updateById(dishDto);

        //修改dish_flavor表中的数据,先删除原数据
        Long id = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, id);
        dishFlavorService.remove(lqw);


        List<DishFlavor> flavors = dishDto.getFlavors();
        //遍历flavors集合,为每一个dishFlavor对象设置id并添加
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
            }
            dishFlavorService.saveBatch(flavors);
        }

        //修改成功后清空缓存数据
        /*Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/

        return R.success(null);
    }

    @DeleteMapping
    @CacheEvict(value = "dish",allEntries = true)
    public R deleteDish(@RequestParam List<Long> ids) {
        for (Long id : ids) {
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
            lqw.eq(DishFlavor::getDishId,id);
            dishFlavorService.remove(lqw);
        }
        dishService.removeByIds(ids);

        //删除成功后清空缓存数据
        /*Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/

        return R.success(null);
    }

    @PostMapping("/status/{status}")
    @CacheEvict(value = "dish",allEntries = true)
    public R updateStatus(@PathVariable Integer status,
                          @RequestParam List<Long> ids){
        /*for (Long id : ids) {
            Dish dish = new Dish();
            dish.setStatus(status);
            dish.setId(id);
            dishService.updateById(dish);
        }*/
        LambdaUpdateWrapper<Dish> luw = new LambdaUpdateWrapper<>();
        luw.in(Dish::getId,ids);
        luw.set(Dish::getStatus,status);
        dishService.update(luw);

        //修改成功后清空缓存数据
        /*Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/

        return R.success("操作成功");
    }

    @GetMapping("/list")
    @Cacheable(value = "dish",key = "#categoryId")
    public R getDishList(@RequestParam Long categoryId){

        List<DishDto> dishes = null;
        //从redis中获取数据
        /*String key = "dish_" + categoryId;
        dishes = (List<DishDto>) redisTemplate.opsForValue().get(key);*/
        //如果有数据,则直接返回数据
        /*if(dishes != null){
            return R.success(dishes);
        }*/
        //如果没有,则查询数据库

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(categoryId != null,Dish::getCategoryId,categoryId);
        List<Dish> list = dishService.list(lqw);
        dishes = new ArrayList<>();
        for (Dish dish : list) {
            DishDto dishDto = new DishDto();
            LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
            qw.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> flavors = dishFlavorService.list(qw);

            BeanUtils.copyProperties(dish,dishDto);
            dishDto.setFlavors(flavors);

            dishes.add(dishDto);
        }

        //查询数据库后,添加缓存
        //redisTemplate.opsForValue().set(key,dishes);

        return R.success(dishes);
    }

}
